package logic

import (
	"context"
	"errors"
	"fmt"
	"math/rand"
	"video-joy/models/cache"
	"video-joy/models/mysql"
	"video-joy/pkg"
	"video-joy/userrpc/internal/svc"
	"video-joy/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 登录及注册
func (l *UserLoginLogic) UserLogin(in *userrpc.UserInfoLoginRequest) (*userrpc.UserInfoLoginResponse, error) {
	// todo: add your logic here and delete this line

	user := &mysql.UserInfo{
		PhoneNum:      in.PhoneNum,
		Pwd:           pkg.Md5(in.Pwd),
		NickName:      fmt.Sprintf("游客_%d", rand.Intn(9000)+1000),
		AvatarLink:    "http://t4kai2dsu.hn-bkt.clouddn.com/OIP-C.jpg",
		AccountStatus: int(in.AccountStatus),
		FollowNum:     int(in.FollowNum),
		FansNum:       int(in.FansNum),
		UserLevel:     in.UserLevel,
	}

	if err := user.UserFindByPhoneNum(mysql.DB, in.PhoneNum); err != nil {
		return nil, errors.New("该手机号已注册")
	}

	if in.LoginType == 1 || in.LoginType == 2 {

		if in.LoginType == 1 {
			if pkg.Md5(in.Pwd) != user.Pwd {
				return nil, errors.New("密码错误")
			}
		}
		if in.LoginType == 2 {

			result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.PhoneNum).Result()

			if result == "" {
				return nil, errors.New("您还没有发送短信验证码")
			}

			if result != in.SmsCode {
				return nil, errors.New("短信验证码错误")
			}
		}
	} else {
		return nil, errors.New("请选择正确的登录方式")
	}
	return &userrpc.UserInfoLoginResponse{
		UserId: int64(user.ID),
	}, nil
}
